package com.alan.sso.share.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/21 11:24
 * @Description: URIBuilder
 */
public class URIBuilder {

    private List<URIParam> params = new ArrayList();
    private String uri = null;

    public URIBuilder(String uri) {
        this.uri = uri;
    }

    public URIBuilder addParameter(String param, String paramValue) {
        this.params.add(new URIBuilder.URIParam(param, paramValue));
        return this;
    }

    public URIBuilder build() throws UnsupportedEncodingException {
        if (this.params.size() > 0) {
            Iterator i$ = this.params.iterator();

            while(i$.hasNext()) {
                URIBuilder.URIParam uriParam = (URIBuilder.URIParam)i$.next();
                uriParam.setParamValue(URLEncoder.encode(uriParam.getParamValue(), "UTF-8"));
            }
        }

        return this;
    }

    @Override
    public String toString() {
        if (this.uri == null) {
            return this.uri;
        } else {
            StringBuilder sb = new StringBuilder(this.uri);
            if (this.params.size() > 0) {
                if (this.uri.lastIndexOf("?") != -1) {
                    sb.append("&");
                } else {
                    sb.append("?");
                }

                for(int i = 0; i < this.params.size(); ++i) {
                    if (i > 0) {
                        sb.append("&");
                    }

                    URIBuilder.URIParam uriParam = (URIBuilder.URIParam)this.params.get(i);
                    sb.append(uriParam.getParam()).append("=").append(uriParam.getParamValue());
                }
            }

            return sb.toString();
        }
    }

    class URIParam {
        private String param;
        private String paramValue;

        public URIParam(String param, String paramValue) {
            this.param = param;
            this.paramValue = paramValue;
        }

        public String getParam() {
            return this.param;
        }

        public String getParamValue() {
            return this.paramValue;
        }

        public void setParamValue(String paramValue) {
            this.paramValue = paramValue;
        }
    }

}
